const express = require('express');
const mongoose = require('mongoose');
const passport = require('passport');
const LocalStrategy = require('passport-local');
const JWTStrategy = require('passport-jwt').Strategy;
const ExtractJWT = require('passport-jwt').ExtractJwt;

const usersRouter = require('./routes/users.js');
const loginRouter = require('./routes/login.js');
const registerRouter = require('./routes/register.js');

const User = require('./models/User.js');

const cors = require('cors');

(async () => {
  try {
    // DeprecationWarning: Mongoose: the `strictQuery` option will be switched back to `false` by default in Mongoose 7.
    mongoose.set('strictQuery', true);
    console.log('Mongodb is connecting');
    await mongoose.connect(process.env.LOC_MONGO_URI).then(() => {
      console.log('Mongodb is connected');
    });

    const app = express();

    // 允许跨域
    app.use(cors());

    // 我们使用了express.json()和express.urlencoded()中间件来解析请求体中的json和表单数据。
    app.use(express.json());
    app.use(express.urlencoded({extended: true}));

    passport.use(new LocalStrategy(User.authenticate('jwt', {session: false})));

    passport.use(
      new JWTStrategy(
        {
          jwtFromRequest: ExtractJWT.fromAuthHeaderAsBearerToken(),
          secretOrKey: process.env.SECRET_KEY
        },
        (jwtPayload, cb) => {
          return User.findById(jwtPayload.userId)
            .then((user) => {
              return cb(null, user);
            })
            .catch((err) => {
              return cb(err);
            });
        }
      )
    );

    // /api/login
    // /api/refreshToken
    // /api/logout
    app.use('/api', loginRouter);

    app.use('/api/register', registerRouter);
    app.use('/api/users', usersRouter);

    const port = process.env.PORT || 3000;

    app.listen(port, () => {
      console.log(`Listening on port ${port}`);
    });
  } catch (error) {
    console.error('[app]', [error]);
  }
})();
